package com.googlecode.c4e.ui.views.internal;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IDeferredWorkbenchAdapter;
import org.eclipse.ui.progress.IElementCollector;

import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.ProjectGroup;

public class ProjectGroupAdapter implements IDeferredWorkbenchAdapter {

	public Object[] getChildren(Object obj) {
		ProjectGroup projectGroup = (ProjectGroup) obj;

		if (projectGroup.getProjects() != null) {
			return projectGroup.getProjects().toArray();
		}
		try {
			projectGroup.setProjects(Registry.getDefault().listProjects(
					projectGroup));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return projectGroup.getProjects().toArray();
	}

	public ImageDescriptor getImageDescriptor(Object obj) {
		return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
				ISharedImages.IMG_OBJ_FOLDER);
	}

	public String getLabel(Object obj) {
		ProjectGroup projectGroup = (ProjectGroup) obj;
		return projectGroup.getName();
	}

	public Object getParent(Object obj) {
		ProjectGroup projectGroup = (ProjectGroup) obj;
		return projectGroup.getServer();
	}

	public void fetchDeferredChildren(Object obj, IElementCollector collector,
			IProgressMonitor monitor) {

		ProjectGroup projectGroup = (ProjectGroup) obj;
		monitor.beginTask("Fetching projects for " + projectGroup.getName(),
				100);

		if (projectGroup.getProjects() != null) {
			monitor.done();
			collector.add(projectGroup.getProjects().toArray(), monitor);
			return;
		}

		try {
			projectGroup.setProjects(Registry.getDefault().listProjects(
					projectGroup));
		} catch (Exception e) {
			monitor.done();
			throw new RuntimeException(e);
		}
		collector.add(projectGroup.getProjects().toArray(), monitor);
		monitor.done();
	}

	public ISchedulingRule getRule(Object obj) {
		ProjectGroup projectGroup = (ProjectGroup) obj;
		return new ProjectGroupAdapterSchedulingRule(projectGroup);
	}

	public boolean isContainer() {
		return true;
	}
}
